package com.fans.jwt.auth.interceptors;

import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.fans.common.utils.BlankUtils;
import com.fans.jwt.auth.interceptors.properties.FeignParamsTransmitProperties;

import feign.RequestInterceptor;

/**
 * 
 * @ClassName: FeignRequestInterceptor
 * @Description: 解决header头部传递问题,以及固定参数传递问题
 * @author fanhaohao
 * @date 2020年1月14日 上午10:26:31
 */
@Component
public class FeignRequestInterceptor {
	private static Logger logger = LoggerFactory.getLogger(FeignRequestInterceptor.class);

	@Autowired
	private FeignParamsTransmitProperties feignParamsTransmitProperties;
	@Bean
	public RequestInterceptor headerInterceptor() {
		return template -> {
			ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
					.getRequestAttributes();
			if (BlankUtils.isNotBlank(attributes)) {
				HttpServletRequest request = attributes.getRequest();
				Enumeration<String> headerNames = request.getHeaderNames();
				// 把头部信息设置到feign后的http请求的头部
				if (headerNames != null) {
					while (headerNames.hasMoreElements()) {
						String name = headerNames.nextElement();
						String values = request.getHeader(name);
						template.header(name, values);
					}
				}
				// 参数信息设置到feign后的http的头部里面
				Enumeration<String> parameterNames = request.getParameterNames();
				if (parameterNames != null) {
					// 获取可传递的参数
					List<String> paramAllows = feignParamsTransmitProperties.getAllows();
					while (parameterNames.hasMoreElements()) {
						String name = parameterNames.nextElement();
						if (paramAllows.contains(name)) {// 可传递的参数
							String values = request.getParameter(name);
							template.header(name, values);
						}
					}
				}
			}
		};
	}
}
